import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:url_launcher/url_launcher.dart';
import './OrderDetail.dart';

/**
 * 待取货订单页面
 */
class WeiFuKuan extends StatefulWidget {
  List list;
  WeiFuKuan(this.list);
  @override
  _WeiFuKuan createState() => _WeiFuKuan();
}

class _WeiFuKuan extends State<WeiFuKuan>
    {
      List orderList=[];
      // 分页当前页
      int page=1;
      // 上拉加载控制器
      RefreshController _refreshController = RefreshController(initialRefresh: false);
      _WeiFuKuan(){
        _onLoading();
      }
      // 刷新时调用
      void _onRefresh() async{
        // monitor network fetch
        //await Future.delayed(Duration(milliseconds: 1000));
        // _onLoading();
        // if failed,use refreshFailed()
        _refreshController.refreshCompleted();
      }

      String riderId;//骑手ID
      // 加载数据的函数
      void _onLoading() async{
        // 获取内存存储的用户id
        SharedPreferences prefs = await SharedPreferences.getInstance();
        riderId = prefs.getString("riderId");
        // monitor network fetch
        // await Future.delayed(Duration(milliseconds: 1000));
        // Response response = await Dio().get("http://xllm.szghrj.com:8082/app/order/searchUserOrder?limit=10&orPeisongType=1&orStatus=0&page=${page}&userId=${userId}");
        // var x = json.decode(response.toString());
        // var x = await HttpUtil().get("/app/order/searchUserOrder?limit=10&orPeisongType=1&orStatus=0&page=$page&userId=$userId");
        var x = await HttpUtil().get("/waimai/rider/getRiderOrders?limit=10&page=${page}&rid=${riderId}&orStatus=2");
        page++;
        if(x['code']==200){
          orderList.addAll(x['data']);
        }
        if(x['data'].length<1){
          _refreshController.loadNoData();
          return;
        }
        // if failed,use loadFailed(),if no data return,use LoadNodata()
        if(mounted){
          setState(() {});
          _refreshController.loadComplete();
        }
      }

      // 显示订单支付按钮/收货按钮
      // Widget showOrderBtn(obj){
      //   String s="";
      //   switch(obj['orStatus']){
      //     case 0:s="立即支付";break;
      //     case 2:s="立即收货";break;
      //   }
      //   return s=="" ? null: Center(child:Text(s,style: TextStyle(color: Colors.white),));
      // }
      // // 显示删除订单按钮
      // Widget showDeleteOrder(obj){
      //   String s="";
      //   switch(obj['orStatus']){
      //     case 0:s="删除订单";break;
      //   }
      //   return s=="" ? null: Center(child:Text(s,style: TextStyle(color: Colors.white),));
      // }
      // // 显示订单状态
      // Widget showOrderStatus(obj){
      //   String s="待付款";
      //   switch(obj['orStatus']){
      //     case 0:s="待付款";break;
      //     case 1:s="代发货";break;
      //     case 2:s="待收货";break;
      //     case 3:s="已完成";break;
      //     case 4:s="退换货中";break;
      //     case 6:s="退款成功";break;
      //   }
      //   return Text(s,style: TextStyle(color: Colors.red),);
      // }
      // 显示订单
      // GestureDetector _showOrders(item,i) {
      //   // 解析订单详情
      //   var orderDetail =(item['orderDetailList']) ;
      //   return GestureDetector(
      //     child: Container( // 一个订单信息
      //       // margin: EdgeInsets.fromLTRB(10, 10, 10, 40 ),
      //         decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(10))),
      //         child:SingleChildScrollView(
      //           child:
      //           Column(
      //             children: [
      //               Row(
      //                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //                 children: [
      //                   Text("官方旗舰店"),
      //                   showOrderStatus(item),
      //                 ],
      //               ),
      //               Row(
      //                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //                 children: [
      //                   CachedNetworkImage(imageUrl: Config.getInstance().getHost()+orderDetail[0]['goods']['gimages'],width: 60,height: 60,),
      //                   Column(children: [
      //                     Container(child: Text("${orderDetail[0]['goods']['gname']}"),),
      //                     Container(child: Text("${orderDetail[0]['goods']['jianjie']}",style: TextStyle(color: Colors.black12),))
      //                   ],),
      //                   Column(children: [
      //                     Container(child: Text("￥${orderDetail[0]['odCost']}"),),
      //                     Container(child: Text("*${orderDetail[0]['odNum']}"),),
      //                   ],)
      //                 ],
      //               ),
      //               Divider(),
      //               Row(
      //                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //                 children: [
      //                   Container(child: Text("共${orderDetail[0]['odNum']}件"),),
      //                   Container(child: Row(children: [
      //                     Container(child: Text("总价:￥${item['orPrice']}",style: TextStyle(color: Colors.black12),),),
      //                     Container(child: Text("实付:￥${item['orPrice']}"),),
      //                   ],)),
      //
      //                 ],
      //               ),
      //               Row(
      //                   mainAxisAlignment: MainAxisAlignment.end,
      //                   children: [
      //                     GestureDetector(child: Container(
      //                       width: 80,
      //                       child: showDeleteOrder(item),
      //                       decoration: BoxDecoration(
      //                         color: Colors.deepOrange,
      //                         borderRadius: BorderRadius.all(Radius.circular(20.0)),
      //                       ),
      //                     ),onTap: () async {
      //                       print("删除订单");
      //                       showDialog<Null>(
      //                         context: context,
      //                         barrierDismissible: false,
      //                         builder: (BuildContext context) {
      //                           return new AlertDialog(
      //                             title: new Text('删除订单'),
      //                             content: Text('确认删除订单?'),
      //                             actions: <Widget>[
      //                               new FlatButton(
      //                                 child: new Text('取消'),
      //                                 onPressed: (){
      //                                   Navigator.of(context).pop();
      //                                 },
      //                               ),
      //                               new FlatButton(
      //                                 child: new Text('确定'),
      //                                 onPressed: () async{
      //                                   var x = await HttpUtil().get("/app/order/deleteOrder?orId=${item['orId']}");
      //                                   if(x['code']==200){
      //                                     setState(() {
      //                                       orderList.removeWhere((element) {
      //                                         return element==orderList[i];
      //                                       });
      //                                     });
      //                                     Fluttertoast.showToast(
      //                                         msg: "订单取消成功",
      //                                         toastLength: Toast.LENGTH_SHORT,
      //                                         gravity: ToastGravity.BOTTOM,
      //                                         timeInSecForIosWeb: 1,
      //                                         backgroundColor: Colors.black45,
      //                                         textColor: Colors.white,
      //                                         fontSize: 16.0
      //                                     );
      //                                   }else{
      //                                     Fluttertoast.showToast(
      //                                         msg: "取消失败",
      //                                         toastLength: Toast.LENGTH_SHORT,
      //                                         gravity: ToastGravity.BOTTOM,
      //                                         timeInSecForIosWeb: 1,
      //                                         backgroundColor: Colors.black45,
      //                                         textColor: Colors.white,
      //                                         fontSize: 16.0
      //                                     );
      //                                   }
      //                                   Navigator.of(context).pop();
      //                                 },
      //                               ),
      //                             ],
      //                           );
      //                         },
      //                       ).then((val) {
      //                         print(val);
      //                       });
      //
      //                     },
      //                     ),
      //                     GestureDetector(child: Container(
      //                         width:100,
      //                         // padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
      //                         child: showOrderBtn(item),
      //                         decoration: BoxDecoration(
      //                           color: Colors.deepOrange,
      //                           borderRadius: BorderRadius.all(Radius.circular(20.0)),
      //                         )
      //                     ),onTap: () async {
      //                       String unionid = item['unionid'];
      //                       double allMoney = item['orPrice'];
      //                     },)
      //                     ]
      //               )
      //             ],
      //           ),
      //         )
      //     ),
      //     onTap: (){
      //       // MyRoute.push(OrderDetail());
      //       Navigator.push(
      //           context,
      //           MaterialPageRoute(
      //             // builder:(context)=>OrderDetail(orid:item['orId'],orStatus: item['orStatus'].toString()),
      //           )
      //       );
      //     },
      //   );
      // }
      // 显示订单
      GestureDetector _showOrders(i) {
        return GestureDetector(
          child: Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 10,horizontal: 20),
            child:Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    orderList[i]['orPayTime']==null ? Text("") : Text("客户已等待"+countMin(orderList[i]['orPayTime'])+"分钟"),
                    SizedBox(width: 10,),
                    GestureDetector(
                      child:Container(
                        color: Colors.amberAccent,
                        child: Text("收到任务"),) ,
                    )
                  ],
                ),
                Divider(),
                Row(
                  children: [
                    Container(padding:EdgeInsets.all(5),child: Text("店",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(color: Colors.blue,borderRadius: BorderRadius.all(Radius.circular(5))),),
                    SizedBox(width: 10,),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(orderList[i]['merchant']['mname']),
                        Text(orderList[i]['merchant']['placedetail'])
                      ],
                    )
                  ],
                ),
                Row(
                  children: [
                    Container(padding: EdgeInsets.all(5),child: Text("客",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(color: Colors.red,borderRadius: BorderRadius.all(Radius.circular(5))),),
                    SizedBox(width: 10,),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(orderList[i]['address']['adName']),
                        Text(orderList[i]['address']['addressDetail'])
                      ],
                    )
                  ],
                ),
                Divider(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    GestureDetector(
                      child:Container(child: Row(children: [Icon(Icons.phone_android_outlined),Text("联系商家")])),
                      onTap: () async{
                        // if( await canLaunch("tel:110")){
                        await launch("tel:"+orderList[i]['merchant']['phone']);
                        // }else{
                        //  throw "拨号失败"; // 模拟器会失败，真机可以拨号
                        // }
                      },),
                    GestureDetector(
                      child:Container(child: Row(children: [Icon(Icons.room_outlined),Text("导航到商家")])),
                      onTap: () async{
                        //  await launch("http://120.24.156.206/test/map.html");// 测试地图
                        // final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
                        //
                        //   geolocator
                        //       .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
                        //       .then((Position position) {
                        //   setState(() {
                        //    print(position);
                        //   });
                        //   }).catchError((e) {
                        //   print(e);
                        //   });
                        // 7.6定位版本
                        final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
                        final position = await _geolocatorPlatform.getCurrentPosition();
                        // print(position); //Latitude: 37.4219983, Longitude: -122.084
                        // 计算两个坐标之间的距离
                        double distanceInMeters = Geolocator.distanceBetween(152.2165157, 16.9437819, 52.3546274, 4.8285838);
                        print(distanceInMeters);
                      },),
                    GestureDetector(
                      child: Container(child: Row(children: [Icon(Icons.list),Text("明细")])),
                      onTap: (){
                        MyRoute.push(OrderDetail(orid:orderList[i]['id']));
                      },
                    )
                  ],
                )
              ],
            )
            ,
          ),onTap: (){
          // MyRoute.push(OrderDetail());
        },
        );
      }

      // @override
      // Widget build(BuildContext context) {
      //   return Scaffold(
      //     body: SmartRefresher(
      //       enablePullDown: false,
      //       enablePullUp: true,
      //       header: WaterDropHeader(),
      //       footer: CustomFooter(
      //         builder: (BuildContext context,LoadStatus mode){
      //           Widget body ;
      //           if(mode==LoadStatus.idle){
      //             body =  Text("上拉加载");
      //           }
      //           else if(mode==LoadStatus.loading){
      //             body =  CupertinoActivityIndicator();
      //           }
      //           else if(mode == LoadStatus.failed){
      //             body = Text("加载失败！点击重试！");
      //           }
      //           else if(mode == LoadStatus.canLoading){
      //             body = Text("松手,加载更多!");
      //           }
      //           else{
      //             body = Text("没有更多数据了!");
      //           }
      //           return Container(
      //             height: 55.0,
      //             child: Center(child:body),
      //           );
      //         },
      //       ),
      //       controller: _refreshController,
      //       onRefresh: _onRefresh,
      //       onLoading: _onLoading,
      //       child: ListView.builder(
      //         itemBuilder: (c, i) => Card(child: _showOrders(orderList[i],i)),
      //         itemExtent: 160.0,    // 每个的高度
      //         itemCount: orderList.length,
      //       ),
      //     ),
      //   );
      // }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SmartRefresher(
            enablePullDown: false,
            enablePullUp: true,
            header: WaterDropHeader(),
            footer: CustomFooter(
              builder: (BuildContext context,LoadStatus mode){
                Widget body ;
                if(mode==LoadStatus.idle){
                  body =  Text("上拉加载");
                }
                else if(mode==LoadStatus.loading){
                  body =  CupertinoActivityIndicator();
                }
                else if(mode == LoadStatus.failed){
                  body = Text("加载失败！点击重试！");
                }
                else if(mode == LoadStatus.canLoading){
                  body = Text("松手,加载更多!");
                }
                else{
                  body = Text("没有更多数据了!");
                }
                return Container(
                  height: 55.0,
                  child: Center(child:body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              itemBuilder: (c, i) => Card(child: _showOrders(i)),
              // itemExtent: 160.0,    // 每个的高度
              itemCount: orderList.length,
            ),
          ),
        );
      }

      @override
      // TODO: implement wantKeepAlive
      bool get wantKeepAlive => true;
      // 计算支付时间与当前时间的分钟数
      String countMin(payTime) {
        var old = DateTime.parse(payTime);
        var now = DateTime.now();
        var min= now.difference(old);
        return min.inMinutes.toString();
      }
    }

